<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="APP名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入APP名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div style="width: 100%;height: 90vh;overflow:auto; margin-bottom: 30%;padding-bottom: 18%;position: relative;">
    <el-table v-loading="loading" :data="cooperationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="APP名称" align="center" prop="name" />
      <el-table-column label="APP介绍" align="center" prop="introduce" :show-overflow-tooltip="true" :formatter="formatHtmlContent"/>
      <el-table-column label="链接地址" align="center" prop="introduce" :show-overflow-tooltip="true" :formatter="formatHtmlContent">
        <template slot-scope="scope">
          <a  @click="handleClick(scope.row.appUrl)" target="_blank" >{{scope.row.appUrl}}</a>
        </template>
      </el-table-column>
      <el-table-column label="icon图标" align="center" prop="icon" >
        <template slot-scope="scope">
          <div class="thumbnail-container"   >
            <img v-if="scope.row.iconUrl" :src="scope.row.iconUrl" class="thumbnail-image" alt="ICON图标"  @click="handleImageClick(scope.row.iconUrl)"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="uploadFile" >
        <template slot-scope="scope">
          <div class="thumbnail-container"   >
            <img v-if="scope.row.uploadUrl" :src="scope.row.uploadUrl" class="thumbnail-image" alt="ICON图标"  @click="handleImageClick(scope.row.uploadUrl)"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            title="修改"
          ></el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            title="删除"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
</div>
    <!-- 添加或修改开放合作对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body :before-close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :inline="true">
        <el-form-item label="APP名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入APP名称" style="width: 202.5px" :disabled="disabled"/>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker clearable
                          v-model="form.createTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择创建时间"
                          style="width: 202.5px"
                          disabled="true">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="链接地址" prop="appUrl">
          <el-input v-model="form.appUrl" type="textarea" placeholder="请输入链接地址" style="width: 495px;" :rows="4"  :disabled="disabled"/>
        </el-form-item>
        <el-form-item label="APP介绍" prop="introduce">
          <el-input v-model="form.introduce" type="textarea" placeholder="请输入内容" style="width: 495px;" :rows="4"  :disabled="disabled"/>
        </el-form-item>
        <el-form-item label="icon图标" prop="icon" style="width: 100%" >
          <file-view  v-if="show"  :limit="1" :type="typeSelect" :businessId="form.icon" :businessCode="businessCode" @getFile="getFile"></file-view>
        </el-form-item>
        <el-form-item label="图片" prop="uploadFile" style="width: 100%" >
          <file-view  v-if="show"  :limit="1" :type="typeSelect" :businessId="form.uploadFile" :businessCode="businessCode" ></file-view>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center; align-items: center;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    预览图片-->
    <el-dialog :visible.sync="openImg" width="33%">
      <img :src="previewImageUrl" class="preview-image" alt="预览" />
    </el-dialog>

  </div>
</template>

<script>
import FileView from "@/components/FileView/index"
import { listCooperation, getCooperation, delCooperation, addCooperation, updateCooperation } from "@/api/open/cooperation";

export default {
  name: "Cooperation",
  components: {FileView},
  data() {
    return {
      // 遮罩层
      loading: true,
      show:false,
      businessCode: "openCooperation",
      openImg:false,
      previewImageUrl:null,
      typeSelect:0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      disabled:false,
      // 开放合作表格数据
      cooperationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      OpenFile:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: 'APP名称不能为空', trigger: 'blur' },
        ],
        appUrl: [
          { required: true, message: '链接地址不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: 'APP介绍不能为空', trigger: 'blur' },
        ],
        icon: [
          { required: true, message: '请上传icon图标', trigger: 'change' }
        ],
      }

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询开放合作列表 */
    getList() {
      this.loading = true;
      listCooperation(this.queryParams).then(response => {
        this.cooperationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleClick(url) {
      if (!url.startsWith('http://') && !url.startsWith('https://')) {
        // 如果没有协议，添加默认的http://协议
        url = 'http://' + url;
      } window.open(url, '_blank');
    },
    handleImageClick(imageUrl) {
      this.previewImageUrl = imageUrl;
      this.openImg = true;
    },
    getFile(data){
      this.form.OpenFile=data[0].id;
    },
    // 取消按钮
    cancel() {
      this.typeSelect=0;
      this.show=false;
      this.open = false;
      this.reset();
    },
    formatHtmlContent(row) {
      console.log(row)
      const title = row.introduce.length > 50 ? row.introduce.substring(0, 80) + '...' : row.introduce;
      // 获取文本内容并返回
      return title || '';
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        icon: null,
        introduce: null,
        uploadFile: null,
        createTime: null,
        belongTo: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },


    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.typeSelect=0;
      // 格式化日期
      const formatDateTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以加1
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      };
      this.form.createTime = formatDateTime(new Date());
      this.form.icon=new Date().getTime()+20;
      this.form.uploadFile=new Date().getTime();
      this.show=true;
      this.open = true;
      this.title = "添加开放合作APP信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCooperation(id).then(response => {
        this.form = response.data;
        this.typeSelect=1;
        //给照片标志附上默认值
        this.form.OpenFile=1;
        this.show=true;
        this.open = true;
        this.title = "修改开放合作";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCooperation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCooperation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据项？').then(function() {
        return delCooperation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>
<style scoped>
.warning-color {
  color: red;
  /* 设置预警条件下的所需样式 */
}

.warning-row {
  background-color: orange;
}
.thumbnail-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 30px;
  /* 确保容器高度占满单元格 */
}

.thumbnail-image {
  object-fit: cover;
  border: 1px solid #ccc; /* 可选，添加边框样式 */
  height: 30px;
}

.preview-image {
  width: 100%;
  height: auto;
}

</style>
